package com.yichuang.security.jwt.main.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsService implements UserDetailsService {

    // 密码编码器
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = "password";
        // 模拟从数据库加载用户信息
        if ("admin".equals(username)) {
            return User.builder()
                    .username("admin")
                    .password(bCryptPasswordEncoder.encode(password)) // 存储时 进行BCryptPasswordEncoder编码
                    .roles("USER")
                    .build();
        } else if ("user".equals(username)) {
            return User.builder()
                    .username("user")
                    .password(bCryptPasswordEncoder.encode(password)) // 存储时 进行BCryptPasswordEncoder编码
                    .roles("USER")
                    .build();
        }
        throw new UsernameNotFoundException("User not found: " + username);
    }
}
